﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.HtmlConverter;


namespace EvTest.SpirePDF
{
    public partial class PdfTo : Form
    {

        private string saveDir = @"D:\EvTest\File\";



        public PdfTo()
        {
            InitializeComponent();
        }

        // PDF转PPT
        private void button1_Click(object sender, EventArgs e)
        {
        }

        //PDF转Word
        private void button2_Click(object sender, EventArgs e)
        {

            //doc地址
            string inputfile = txtInput.Text.Trim();


            PdfDocument doc = new PdfDocument();


            if (dgv.Rows.Count <= 0)
            {
                MessageBox.Show("您还未选择任何文件");
                return;
            }



            foreach (DataGridViewRow r in dgv.Rows)
            {
                doc.LoadFromFile(r.Cells[0].Value.ToString()); ;

                string savename = r.Cells[1].Value.ToString() + ".docx";

                doc.SaveToFile(saveDir + savename, FileFormat.DOCX);

                doc.Close();

                //System.Diagnostics.Process.Start(savename);
            }

            MessageBox.Show("文件转换已完成，即将打开输出文件夹");

            System.Diagnostics.Process.Start("explorer.exe", saveDir);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Pdf file
            string inputfile = txtInput.Text.Trim();

            //Open pdf document
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(inputfile);

            //Save to images
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                String fileName = saveDir + String.Format("ToImage-img-{0}.png", i);
                using (Image image = doc.SaveAsImage(i, 300, 300))
                {
                    image.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                    System.Diagnostics.Process.Start(fileName);
                }
            }

            doc.Close();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //Open pdf document
            PdfDocument doc = new PdfDocument();

            if (dgv.Rows.Count <= 0)
            {
                MessageBox.Show("您还未选择任何文件");
                return;
            }

            foreach (DataGridViewRow r in dgv.Rows)
            {
                string inputfile = r.Cells[0].Value.ToString();
                string savefile = saveDir + "ToHTML" + r.Index + ".html";

                doc.LoadFromFile(inputfile);
                doc.SaveToFile(savefile, FileFormat.HTML);
                doc.Close();

                System.Diagnostics.Process.Start(savefile);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {

            //Get text from .txt file
            string text = "Spire.PDF for .NET更新至v7.8.2，该版本支持添加不可见的数字签名的功能，增强了转换PDF到图片/SVG的功能。此外，本次更新还修复了打印PDF文档时出现的问题，欢迎下载体验。";

            //Create a pdf document
            PdfDocument doc = new PdfDocument();

            PdfSection section = doc.Sections.Add();
            PdfPageBase page = section.Pages.Add();

            //这里智能识别英语，需要解决
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 20);

            //Set string format
            PdfStringFormat format = new PdfStringFormat();
            format.LineSpacing = 20f;

            PdfBrush brush = PdfBrushes.Black;

            //Set text layout
            PdfTextLayout textLayout = new PdfTextLayout();
            textLayout.Break = PdfLayoutBreakType.FitPage;
            textLayout.Layout = PdfLayoutType.Paginate;

            RectangleF bounds = new RectangleF(new PointF(10, 20), page.Canvas.ClientSize);

            PdfTextWidget textWidget = new PdfTextWidget(text, font, brush);
            textWidget.StringFormat = format;
            textWidget.Draw(page, bounds, textLayout);

            string output = saveDir + "TextToPdf.pdf";

            //Save to file
            doc.SaveToFile(output, FileFormat.PDF);

            //Launch the result file
            PDFDocumentViewer(output);


        }


        private void PDFDocumentViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

        private void button6_Click(object sender, EventArgs e)
        {

            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            PdfPageSettings pgSt = new PdfPageSettings();
            pgSt.Size = PdfPageSize.A4;

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
            htmlLayoutFormat.IsWaiting = false;

            string source = @"<ul>
            <li><h2> 致尊敬的Stimulsoft用户：</h2></li>
            <li><p style ='line-height:1.75;padding:15px 20px 0;'> 本周Stimulsoft官方举办的黑色星期五7.5折优惠已经正式结束了（11.26 - 11.29），还未采购的朋友可以参与慧都网18周年庆特惠。</p></li>
            <li>在周年特惠期间，您将享有采购优惠、满额送福利的特权</li>
            </ul> ";

            doc.LoadFromHTML(source, true, pgSt, htmlLayoutFormat);

            //Save pdf file.
            doc.SaveToFile(saveDir + "FromHTML.pdf");
            doc.Close();

            //Launch the file.
            PDFDocumentViewer(saveDir + "FromHTML.pdf");
        }

        private void button7_Click(object sender, EventArgs e)
        {

            using (PdfDocument pdfDocument = new PdfDocument())
            {
                //Load Tiff file
                Image tiffImage = Image.FromFile(@"d:\\CERT-Associate-Data-Analyst-600x600.png");
                //Split Tiff to images
                Image[] images = SplitTIFFImage(tiffImage);
                for (int i = 0; i < images.Length; i++)
                {
                    PdfImage pdfImg = PdfImage.FromImage(images[i]);
                    PdfPageBase page = pdfDocument.Pages.Add();
                    //Scale image
                    float width = pdfImg.Width * 0.7f;
                    float height = pdfImg.Height * 0.7f;
                    float x = (page.Canvas.ClientSize.Width - width) / 2;
                    //Draw imge on the page
                    page.Canvas.DrawImage(pdfImg, x, 0, width, height);
                }

                string result = saveDir + "TiffToPdf-result.pdf";
                //Save to file
                pdfDocument.SaveToFile(result);

                //Launch the result file
                PDFDocumentViewer(result);
            }

        }

        public static Image[] SplitTIFFImage(Image tiffImage)
        {
            int frameCount = tiffImage.GetFrameCount(FrameDimension.Page);
            Image[] images = new Image[frameCount];
            Guid objGuid = tiffImage.FrameDimensionsList[0];
            FrameDimension objDimension = new FrameDimension(objGuid);
            for (int i = 0; i < frameCount; i++)
            {
                tiffImage.SelectActiveFrame(objDimension, i);
                using (MemoryStream ms = new MemoryStream())
                {
                    tiffImage.Save(ms, ImageFormat.Png);
                    images[i] = Image.FromStream(ms);
                }
            }
            return images;

        }

        private void button8_Click(object sender, EventArgs e)
        {

        }

        // 选择文件呀
        private void button9_Click(object sender, EventArgs e)
        {
            OpenFileDialog odf = new OpenFileDialog();
            odf.Multiselect = true;
            odf.RestoreDirectory = true;
            odf.Title = "打开你所选取的文件";

            if (odf.ShowDialog() == DialogResult.OK)
            {
                if (odf.FileNames.Length == 0)
                {
                    MessageBox.Show("您未选择任何文件");
                    return;
                }

                for (int i = 0; i < odf.FileNames.Length; i++)
                {
                    dgv.Rows.Add(odf.FileNames[i], odf.SafeFileNames[i]);
                }

            }

        }

        private void dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgv.Rows[e.RowIndex].Selected == false)
                    {
                        dgv.ClearSelection();
                        dgv.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dgv.SelectedRows.Count == 1)
                    {
                        //dgv.CurrentCell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];
                        //弹出操作菜单
                        cmsDelete.Show(MousePosition.X, MousePosition.Y);
                    }
                }
            }
        }

        private void cmsDelete_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.ImageIndex == 0)
            {
                // 获得被选中的dgv.rows.index 然后删除

                for (int j = 0; j < this.dgv.Rows.Count; j++)
                {
                    if (this.dgv.SelectedRows.Count > 0)
                    {
                        DataRowView drv = this.dgv.SelectedRows[0].DataBoundItem as DataRowView;
                        drv.Delete();
                    }
                }
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                txtFilename.Text = fbd.SelectedPath;
                saveDir = fbd.SelectedPath;
            }
        }
    }
}
